var express = require('express');
var router = express.Router();
const multer = require('multer');
const { uuid } = require('../utils/utils')

const API = require("../db/upload")
router.get('/getFileList', API.getFileList);
router.post('/addFileItem', (req, res) => {
  const storage = multer.diskStorage({
    destination: 'public/images/',
    filename: function (req, file, cb) {
      const url = uuid() + '-' + file.originalname
      req.file = { ...file, url }
      cb(null, url);
    }
  });

  const uploads = multer({
    storage: storage,
    limits: { fileSize: 10000000 },
  }).any();

  uploads(req, res, (err) => {
    if (err) {
      res.sends(err);
    } else {
      if (req.file == undefined) {
        res.sends(err);
      } else {
        API.addFileItem({ body: { url: 'http://1.92.146.28:1024/images/' + req.file.url, fileName: req.file.url }, userId: req.userId }, res)

      }
    }
  });

});

module.exports = router;